package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.WechatService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Yzxxn
 */
@Service
public class WechatServiceImpl implements WechatService {

    // 登录请求路径
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session";

    // 获取用户手机号请求路径
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    // 获取用户token请求路径
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";


    @Value("${wechat.appId}")
    private String appId;

    @Value("${wechat.appSecret}")
    private String secret;


    /**
     * 获取微信用户openID
     *
     * @param code
     * @return
     */
    @Override
    public String getOpenId(String code) {
        //1、封装请求参数
        Map<String, Object> paramMap = getAppConfig();
        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");

        //2、发送请求
        String result = HttpUtil.get(REQUEST_URL, paramMap);
        JSONObject jsonObject = JSONUtil.parseObj(result);

        //3、获取openID
        return jsonObject.getStr("openid");
    }


    /**
     * 获取微信用户手机号
     *
     * @param phoneCode
     * @return
     */
    @Override
    public String getPhone(String phoneCode) {
        //1、封装请求参数
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("code", phoneCode);

        //2、调用api
        String result = HttpUtil.post(PHONE_REQUEST_URL + getToken(), JSONUtil.toJsonStr(paramMap));

        //3、判断接口响应是否出错
        cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(result);
        if (jsonObject.getInt("errcode") != 0) {
            throw new BaseException("获取微信用户手机号失败！");
        }

        return jsonObject.getJSONObject("phone_info").getStr("purePhoneNumber");
    }


    /**
     * 获取token
     *
     * @return
     */
    public String getToken() {
        //1、封装请求参数
        Map<String, Object> paramMap = getAppConfig();
        paramMap.put("grant_type", "client_credential");

        //2、调用api
        String result = HttpUtil.get(TOKEN_URL, paramMap);
        cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(result);

        //3、处理返回参数
        return jsonObject.getStr("access_token");
    }

    @NotNull
    private Map<String, Object> getAppConfig() {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", appId);
        paramMap.put("secret", secret);
        return paramMap;
    }
}
